package com.eatme.web.security.authentication.wechat.applet.provider;

import com.eatme.web.app.customer.entity.TbUser;
import com.eatme.web.security.authentication.domain.entity.SecurityUser;
import com.eatme.web.security.authentication.domain.entity.SecurityUserAuth;
import com.eatme.web.security.authentication.wechat.applet.service.impl.WechatAppletSecurityUserServiceImpl;
import com.eatme.web.security.authentication.wechat.applet.authentication.WechatAppletAuthenticationToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import java.util.Arrays;
import java.util.Collections;

public class WechatAppletAuthenticationProvider implements AuthenticationProvider {

    private static final Logger LOG = LoggerFactory.getLogger(WechatAppletAuthenticationProvider.class);

    public final WechatAppletSecurityUserServiceImpl wechatAppletSecurityUserServiceImpl;

    public WechatAppletAuthenticationProvider(WechatAppletSecurityUserServiceImpl wechatAppletSecurityUserServiceImpl) {
        this.wechatAppletSecurityUserServiceImpl = wechatAppletSecurityUserServiceImpl;
    }


    /**
     * 认证
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (!supports(authentication.getClass())) {
            return null;
        }
        LOG.info("AppAuthenticationToken authentication request: %s", authentication);
        WechatAppletAuthenticationToken token = (WechatAppletAuthenticationToken) authentication;

        // 从数据库查询 数据
        SecurityUserAuth securityUserAuth = wechatAppletSecurityUserServiceImpl.findByOpenId((String) token.getPrincipal());
        LOG.info("{}",token.getPrincipal());
        if (securityUserAuth == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        SecurityUser user = new SecurityUser();
        user.setList(Arrays.asList(securityUserAuth));
        // LOG.info("{}",user.getAuthorities());
        WechatAppletAuthenticationToken result = new WechatAppletAuthenticationToken(user,token.getSession_key(), Collections.emptyList());
        /*
        Details 中包含了 ip地址、 sessionId 等等属性 也可以存储一些自己想要放进去的内容
        */
        result.setDetails(token.getDetails());
        return result;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return WechatAppletAuthenticationToken.class.isAssignableFrom(aClass);
    }



}